package com.vastcom.fabric.server.action;


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.vastcom.fabric.server.service.FabricService;
import com.vastcom.fabric.server.to.BlockChain;
import com.vastcom.fabric.server.to.HistoryBlockChain;
import com.vastcom.fabric.server.to.PageParmTo;
import com.vastcom.fabric.server.tools.Const;
import com.vastcom.fabric.server.tools.FabricClient;
import com.vastcom.fabric.server.tools.UserContext;
import com.vastcom.fabric.server.tools.UserUtils;
import org.hyperledger.fabric.sdk.Orderer;
import org.hyperledger.fabric.sdk.Peer;
import org.hyperledger.fabric.sdk.TransactionRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("/public")

public class publicAction {
    private static Logger log= LoggerFactory.getLogger(publicAction.class);

    @Autowired
    private FabricService fabricService;


    @GetMapping("testHello")
    @ResponseBody
    public HashMap testHello() {
        log.error("hh");
        log.info("info");
        HashMap hashMap = new HashMap();
        hashMap.put("msg", "Hello World1!");
        return hashMap;
    }


    @PostMapping("testChainQuery")
    @ResponseBody
    public HashMap testChainQuery(@RequestBody PageParmTo parm) throws Exception {

        HashMap m = new HashMap();

        HashMap result = new HashMap();
        try {


            UserContext userContext = fabricService.getMyUserContext();
            FabricClient fabricClient = new FabricClient(userContext);
            log.info("PublicAction-testChainQuery");

            Peer peer = fabricClient.getPeerByName(Const.PEER_RAW_MATERIA_NAME);

            List<Peer> peers = new ArrayList<Peer>();
            peers.add(peer);
            //peers.add(peer1);
            String str = parm.getParm();
            String initArgs[] = {str};
//            log.info("333333333333333333333"+str);

/*            m = fabricClient.queryChaincode(peers, "mychannel", TransactionRequest.Type.GO_LANG
                    , "zzytest", "get", initArgs);
            result = new HashMap();
            Iterator iter = m.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                System.out.println(key + ":" + value);
//                log.info(key+"===4444444444444444444===="+value);
            }


            String resultstr = (String) m.get("result");
//            log.info("4444444444444444444"+resultstr.length());

            resultstr.replace("\\","");
            BlockChain blockChain = new Gson().fromJson(resultstr, BlockChain.class);*/

            BlockChain blockChain = new BlockChain();
            m=fabricClient.queryChaincode(peers,"mychannel", TransactionRequest.Type.GO_LANG
                    ,"zzytest","gethistory",initArgs);
            String strtemp="";
            log.info("++=========="+m.size());

            if(m.get("result")!=null){

                strtemp= (String) m.get("result");
                strtemp.replace("\\","");
                List<HistoryBlockChain> list = new Gson().fromJson(strtemp, new TypeToken<List<HistoryBlockChain>>() {
                }.getType());
                for (HistoryBlockChain historyBlockChain : list) {
                    log.info("++"+historyBlockChain.getValue().getBsj());

                    if(historyBlockChain.getValue().getBsj()!=null){
                        blockChain = historyBlockChain.getValue();
                        break;
                    }
                }
                log.info("++==========111111"+blockChain.getBcry());
            }
            log.info("++==========222222"+blockChain.getBcry());

            result.put("msg","ok");
            result.put("obj",blockChain);
        } catch (JsonSyntaxException e) {
            result.put("msg","error");
            e.printStackTrace();
        }
        return result;
    }



    @PostMapping("getHistoryByKeyForHistory")
    @ResponseBody
    public HashMap getHistoryByKeyForHistory(@RequestBody PageParmTo pageParmTo) throws Exception{

        HashMap m=new HashMap();
        HashMap result=new HashMap();

        UserContext userContext=fabricService.getMyUserContext();
        FabricClient fabricClient=new FabricClient(userContext);
        Peer peer=fabricClient.getPeerByName(Const.PEER_RAW_MATERIA_NAME);
        log.info("PUBLICgetHistoryByKeyForHistory++++++++++++++++"+pageParmTo.getParm());

        List<Peer> peers = new ArrayList<Peer>();
        peers.add(peer);
        //peers.add(peer1);
        String initArgs[] ={pageParmTo.getParm()};
        m=fabricClient.queryChaincode(peers,"mychannel", TransactionRequest.Type.GO_LANG
                ,"zzytest","gethistory",initArgs);
        String strtemp="";
        if(m.get("result")!=null){
            strtemp= (String) m.get("result");
            log.info("before"+strtemp);
            strtemp.replace("\\","");
            log.info("after"+strtemp);
            List<HistoryBlockChain> list = new Gson().fromJson(strtemp, new TypeToken<List<HistoryBlockChain>>() {
            }.getType());
            result.put("list",list);
            result.put("msg","ok");
        }else{
            result.put("msg","error");
        }

        return result;
    }


    @PostMapping("invokeByJson")
    @ResponseBody
    public boolean invokeByJson(@RequestParam("key") String key, @RequestParam("value") String value) throws Exception {
        HashMap m = new HashMap();
        try {
            log.info("PublicAction-invokeByJson");

            FabricClient fabricClient = new FabricClient(fabricService.getMyUserContext());
            Peer peer0 = fabricClient.getPeerByName(Const.PEER_RAW_MATERIA_NAME);

            List<Peer> peerList = new ArrayList<>();
            peerList.add(peer0);

            Orderer orderer = fabricClient.getOrder();

            //String initArgs[]={"\"110114\",\"{\\\"name\\\":\\\"zhangsan\\\",\\\"identity\\\":\\\"110114\\\",\\\"mobile\\\":\\\"18910012222\\\"}\"}"};
            String initArgs[] = {"a", key, value};
            //boolean flag= fabricClient.invoke("test", TransactionRequest.Type.GO_LANG,"basicinfo",orderer,peerList,"invoke",initArgs);
            boolean flag=fabricClient.invoke("mychannel", TransactionRequest.Type.GO_LANG,"zzytest",orderer,peerList,"set",initArgs);

//            boolean flag = fabricClient.invoke("sigma", TransactionRequest.Type.GO_LANG, "test", orderer, peerList, "setjsondata", initArgs);
            if (flag) {
                return true;
            } else {
                return false;

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

}
